# -*- coding: utf-8 -*-
import time, os
import threading
import asyncio
import json
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.log
# import dmclient
import GCL
from MouseCtrl import onMsg

class ConnectHandler(tornado.websocket.WebSocketHandler) :
    def check_origin(self, origin) :
        '''重写同源检查 解决跨域问题'''
        return True

    def open(self) :
        # GCL.showInfo("客户端正在连接……")
        pass

    def on_close(self) :
        GCL.showInfo("客户端连接断开")

    def on_message(self, message) :
        print("td msg:" + message)
        msg = json.loads(message)
        if 'act' in msg:
            if msg['act']=='auth':
                GCL.showInfo(msg)
                resp = {
                    "act": "auth_resp",
                    "myid": GCL.clientid
                }
                self.write_message(json.dumps(resp))
                return None
        onMsg(msg)
        return None
        #
        # # GCL.showInfo("tornado：" + message)
        # if g_queueMsg.qsize()>30:
        #     print("抛弃不重要数据%d"%g_queueMsg.qsize())
        #     g_queueMsg.queue.clear()
        # g_queueMsg.put(message, block=False)


class MainHandler(tornado.web.RequestHandler) :
    def get(self) :
        # logging.getLogger("tornado.access").info("/index.html")
        self.render("index.html")

#
# class CmdHandler(tornado.web.RequestHandler) :
#     def get(self):
#         if 'exit' == self.get_argument("cmd"):
#             g_server.stop()
#             g_dmcprocess.terminate()
#             time.sleep(1)
#             self.write("ok")


class Application(tornado.web.Application) :
    def __init__(self) :
        handlers = [
            (r'/', MainHandler),
            # (r'/cmd', CmdHandler),
            (r'/ws', ConnectHandler),
            (r"/static/(.*)", tornado.web.StaticFileHandler,
             {"path": os.path.join(os.path.dirname(__file__), "static")}),
        ]
        tornado.web.Application.__init__(self, handlers, cookie_secret="dishfiewhnweufjos")




def tornadorun():
    # global g_server
    asyncio.set_event_loop(asyncio.new_event_loop())
    tornadoapp = Application()
    ports = [7800, 7813, 6814, 8815]
    for port in ports:
        try:
            # g_server = \
            tornadoapp.listen(port)
            break
        except OSError as e:
            continue
    GCL.localport = port
    tornado.ioloop.IOLoop.current().start()


def TDServerStart():
    thread1 = threading.Thread(target=tornadorun)
    thread1.setDaemon(True)
    thread1.start()

    #
    # thread3 = threading.Thread(target=TickMsgLoop)
    # thread3.setDaemon(True)
    # thread3.start()


if __name__ == "__main__":
    tornadorun()